<template>

  <div>

    <!--搜索框部分-->
    <el-card>

      <el-form inline label-width="90px" size="mini" class="demo-form-inline">

        <el-form-item label="网站名称">
          <el-input placeholder="请输入内容" v-model.trim="searchWebsiteParam.name" clearable size="mini"></el-input>
        </el-form-item>

        <el-form-item label="网址类型">
          <el-select v-model="searchWebsiteParam.typeId" placeholder="请选择网址类型" clearable>
            <el-option
              v-for="item in websiteTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否常用">
          <el-select v-model="searchWebsiteParam.commonlyUsed" placeholder="请选择是否常用" clearable>
            <el-option label="不常用" value="1"></el-option>
            <el-option label="常用" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序方式">
          <el-select v-model="searchWebsiteParam.sort" placeholder="请选择排序方式" clearable>
            <el-option label="更新时间" value="update_time"></el-option>
            <el-option label="创建时间" value="create_time"></el-option>
            <el-option label="网址类型" value="type_id"></el-option>
            <el-option label="网站名称" value="name"></el-option>
            <el-option label="点击次数" value="number_of_clicks"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" size="mini" @click="getWebList">查询</el-button>
          <el-button type="warning" size="mini" @click="resetQueryWebsite">重置</el-button>
          <el-button type="warning" size="mini" @click="openSaveWebsite">新增</el-button>
          <el-button type="success" size="mini" @click="checkConnection">检查网站是否有效</el-button>
        </el-form-item>

      </el-form>

    </el-card>


    <el-card style="margin-top: 10px">

      <el-table
        :data="websiteTableData"
        max-height="670px"
        height="670px"
        style="width: 100%">

        <el-table-column
          prop="name"
          label="网站名称"
          width="120"
        >
          <template slot-scope="scope">
            <!--检查中-->
            <span v-if="scope.row.check === 1">
              <el-tooltip class="item" effect="dark" content="检查中" placement="top-start">
                <i style="color: #909399" class="el-icon-loading"></i>
              </el-tooltip>
            </span>
            <!--通过-->
            <span v-else-if="scope.row.check === 2">
              <el-tooltip class="item" effect="dark" content="网站检查通过" placement="top-start">
                <i style="color: #67C23A" class="el-icon-success"></i>
              </el-tooltip>
            </span>
            <!--不通过-->
            <span v-else-if="scope.row.check === 3">
              <el-tooltip class="item" effect="dark" content="网站检查不通过" placement="top-start">
                <i style="color: #F56C6C" class="el-icon-error"></i>
              </el-tooltip>
            </span>
            <!--要翻墙-->
            <span v-else-if="scope.row.check === 4">
              <el-tooltip class="item" effect="dark" content="需要翻墙访问" placement="top-start">
                <i style="color: #E6A23C" class="el-icon-question"></i>
              </el-tooltip>
            </span>
            <!--跳过检测-->
            <span v-else-if="scope.row.check === 5">
              <el-tooltip class="item" effect="dark" content="跳过检测（需要翻墙）" placement="top-start">
                <i style="color: #909399" class="el-icon-minus"></i>
              </el-tooltip>
            </span>
            <!--不显示-->
            <span v-else></span>
            &nbsp;{{scope.row.name}}
          </template>
        </el-table-column>

        <el-table-column
          prop="url"
          show-overflow-tooltip
          label="网址"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-link @click="addOneClick(scope.row)" type="primary"> {{scope.row.url}}</el-link>
          </template>
        </el-table-column>

        <el-table-column
          prop="websiteTypeName"
          label="网址类型"
        >
        </el-table-column>

        <el-table-column
          prop="describe"
          label="描述"
        >
        </el-table-column>

        <el-table-column
          prop="numberOfClicks"
          label="点击次数"
        >
        </el-table-column>

        <el-table-column
          prop="commonlyUsed"
          label="是否常用"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.commonlyUsed === 2">
              <el-tag size="small" type="success">常用</el-tag>
            </div>
            <div v-else>
              <el-tag size="small" type="">不常用</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="overTheWall"
          label="是否要翻墙"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.overTheWall === 1">
              <el-tag size="small" type="success">不需要</el-tag>
            </div>
            <div v-else>
              <el-tag size="small" type="">需要</el-tag>
            </div>
          </template>
        </el-table-column>


        <el-table-column
          fixed="right"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button @click="toOpenWebsiteDetailed(scope.row)" type="text" size="small"><i class="el-icon-view"></i>查看</el-button>
            <el-button @click="openUpdWebsite(scope.row)" type="text" size="small"><i class="el-icon-edit"></i>编辑</el-button>
            <el-button @click="delWebsiteByIdTips(scope.row)" type="text" size="small"><i class="el-icon-delete"></i>删除</el-button>
          </template>
        </el-table-column>

      </el-table>


    </el-card>


    <WebsiteDetailed ref="websiteDetailedRef"></WebsiteDetailed>
    <WebsiteSaveUpd ref="websiteSaveUpdRef" @getWebList="getWebList"></WebsiteSaveUpd>

  </div>

</template>

<script>

import http from '@/utils/http'
import WebsiteDetailed from './WebsiteDetailed.vue'
import WebsiteSaveUpd from './WebsiteSaveUpd.vue'

export default {
  name: "WebsiteList",
  components: {
    WebsiteDetailed,
    WebsiteSaveUpd,
  },
  data(){
    return {
      // 网址类型
      websiteTypeList: [],
      // 查询参数
      searchWebsiteParam: {
        typeId: null,
        name: null,
        commonlyUsed: null,
        // 排序字段
        sort: 'number_of_clicks',
      },
      // 表格中的数据
      websiteTableData: [],
      // 检查是否正在进行中
      isChecking: false,
    }
  },
  methods: {
    /**
     * 网址新增了一次点击事件
     * @param row 当前行数据
     */
    addOneClick(row){
      window.open(row.url,'_blank')
      http.post("/web/addOneClick", {
        id: row.id,
      }).then(response => {
        let res = response.data;
        if (res.status === 'error'){
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 根据ID删除网址 提示信息
     */
    delWebsiteByIdTips(row){
      this.$confirm('是否删除该网址, 删除后无法恢复，是否继续?', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消删除',
        type: 'warning'
      }).then(() => {
        // 确定删除
        this.delWebsiteById(row)

      }).catch(() => {
        // 取消删除
      });
    },
    /**
     * 物理删除网址
     * @param row
     */
    delWebsiteById(row){
      http.post("/web/delWebsiteById", {
        id: row.id,
      }).then(response => {
        let res = response.data;
        if (res.status === 'error'){
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }
        this.getWebList()
        this.$message.success("删除成功");

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 打开编辑弹出框
     * @param row 当前行数据
     */
    openUpdWebsite(row){
      this.$refs.websiteSaveUpdRef.openPageWebsite('upd', row, this.websiteTypeList)
    },
    /**
     * 跳转打开网站详情
     * @param row 当前行数据
     */
    toOpenWebsiteDetailed(row){
      this.$refs.websiteDetailedRef.openWebsiteDetailed(row)
    },
    /**
     * 获取网址类型
     */
    getWebsiteType(){
      http.post("/web/getWebsiteType", {}).then(response => {
        let res = response.data;
        if (res.status === 'error'){
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        this.websiteTypeList = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 检查是否连接通过
     */
    async checkConnection() {
      if (this.isChecking) {
        this.$message.warning('检查正在进行中，请稍候...');
        return;
      }

      if (!this.websiteTableData || this.websiteTableData.length === 0) {
        this.$message.warning('没有数据可检查');
        return;
      }

      this.isChecking = true;
      this.$message.info('开始检查网站有效性...');

      // 重置所有检查状态
      this.websiteTableData.forEach(item => {
        if (item.overTheWall !== 1) {
          // 需要翻墙的网站标记为跳过
          this.$set(item, 'check', 5);
        } else {
          // 其他网站重置状态
          this.$set(item, 'check', null);
        }
      });

      // 过滤出不需要翻墙的网站进行检查
      const websitesToCheck = this.websiteTableData.filter(item => item.overTheWall === 1);

      // 依次检查每个网站
      for (let i = 0; i < websitesToCheck.length; i++) {
        const item = websitesToCheck[i];
        await this.checkSingleWebsite(item, i);
      }

      this.isChecking = false;
      this.$message.success('网站检查完成');
    },

    /**
     * 检查单个网站
     * @param {Object} item 网站对象
     * @param {number} index 索引
     */
    async checkSingleWebsite(item, index) {
      try {
        // 设置检查中状态
        this.$set(item, 'check', 1);

        // 使用fetch API检查网站
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

        const response = await fetch(item.url, {
          method: 'HEAD',
          mode: 'no-cors',
          signal: controller.signal
        });

        clearTimeout(timeoutId);

        // 如果能到达这里，说明网站基本可访问
        this.$set(item, 'check', 2);

      } catch (error) {
        // 处理各种错误情况
        if (error.name === 'AbortError') {
          // 超时错误
          this.$set(item, 'check', 3);
        } else if (error.name === 'TypeError') {
          // CORS错误或其他网络错误 - 尝试使用图片方式检测
          await this.checkWithImage(item);
        } else {
          // 其他错误
          this.$set(item, 'check', 3);
        }
      }
    },

    /**
     * 使用图片加载方式检查网站（避免CORS限制）
     * @param {Object} item 网站对象
     */
    checkWithImage(item) {
      return new Promise((resolve) => {
        const img = new Image();
        let timer;

        img.onload = () => {
          clearTimeout(timer);
          this.$set(item, 'check', 2); // 成功
          resolve();
        };

        img.onerror = () => {
          clearTimeout(timer);
          this.$set(item, 'check', 3); // 失败
          resolve();
        };

        // 设置超时
        timer = setTimeout(() => {
          img.onload = null;
          img.onerror = null;
          this.$set(item, 'check', 3); // 超时
          resolve();
        }, 8000);

        // 尝试加载网站favicon
        try {
          const url = new URL(item.url);
          const faviconUrl = `${url.origin}/favicon.ico`;
          img.src = faviconUrl;
        } catch (e) {
          // 如果URL解析失败，直接标记为失败
          this.$set(item, 'check', 3);
          resolve();
        }
      });
    },
    /**
     * 查询全部网址信息
     */
    getWebList(){
      http.post("/web/getWebList", this.searchWebsiteParam).then(response => {
        let res = response.data;
        if (res.status === 'error'){
          // 401是token过期跳转的
          if (res.code !== 401){
            this.$message.error(res.msg);
          }
          return
        }

        // 处理数据
        this.websiteTableData = res.data

      }).catch(error => {
        this.$message.error(error.message);
      })
    },
    /**
     * 重置查询参数
     */
    resetQueryWebsite(){
      this.searchWebsiteParam = {
        typeId: null,
        name: null,
        commonlyUsed: null,
        sort: 'update_time',
      }
    },
    /**
     * 打开新增的弹出框
     */
    openSaveWebsite(){
      this.$refs.websiteSaveUpdRef.openPageWebsite('save', null, this.websiteTypeList)
    },
  },
  mounted(){
    this.getWebsiteType()
    this.getWebList()
  }
}
</script>

<style scoped>

</style>
